package com.training1.core.modules.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.training1.core.common.service.CrudService;
import com.training1.core.common.utils.DateUtils;
import com.training1.core.entity.ContractDetEntity;
import com.training1.core.modules.dao.ContractDetDao;

@Service
@Transactional
public class ContractDetService extends CrudService<ContractDetDao,ContractDetEntity>{
	
	

	@Resource
	private ContractDetDao contractDetDao;
	
	/**
	 * 根据合同id　查询合同详情
	 * @param keyWord
	 * @return
	 */
	public List<ContractDetEntity>  findListById(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<ContractDetEntity> contractList = contractDetDao.findContractExeById(map);
		
		return contractList;
	}
	/**
	 * 保存合同执行信息
	 * @param id
	 * @return
	 */
	public String save(String id, String receiveCyc, String receiveDate ,String receiveAmount) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("id", id);
		ContractDetEntity contractExeEntity = contractDetDao.getRecentContractById(param);
		if(contractExeEntity == null){
			return "4";
		}
		if(!receiveCyc.trim().equals(String.valueOf(contractExeEntity.getCyc()))){
			return "2";//不是最近收款那期
		}else if(contractExeEntity.getExpectDate().after(DateUtils.parseDate(receiveDate))){
			return "3";//收款日期必须大于等于改期预期还款日期
		}else{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);
			map.put("cyc", receiveCyc);
			ContractDetEntity contractExe = contractDetDao.getByContractBaseId(map);
			String status = contractExe.getStatus().trim();
			//当期执行状态是0 不更新，1更新成2
			if("1".equals(status)){
				contractExe.setStatus("2");
			}
			contractExe.setActualDate(DateUtils.parseDate(receiveDate));
			contractExe.setActualAmount(new BigDecimal(receiveAmount));
			//更新合同执行信息表
			contractDetDao.update(contractExe);
			
			ContractDetEntity LastContract = contractDetDao.getLastContract(map);
			//最后一期收款结束，更新合同基本信息表
			if(LastContract.getActualDate() != null ){
			
				String statusEnum = "90";
				Date endDate =LastContract.getActualDate();
				BigDecimal totalAmount = LastContract.getTotalBaseAmount().add(LastContract.getTotalAddAmount()).add(LastContract.getTotalDelayAmount());
				Date expectDate = LastContract.getExpectDate();
				if(expectDate.after(new Date())){
					statusEnum = "20";
				}
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("id",id);
				map1.put("status",statusEnum);
				map1.put("endDate", endDate);
				map1.put("totalAmount", totalAmount);
				contractDetDao.updateContractBase(map1);
			}
			 return "1";
		}
		
	}
}
